<template>
  <div style="display: flex; height: 100%">
    <!-- 行政区域树 -->
    <div style="width: 300px; border-right: 1px solid #ccc; padding: 10px">
      <el-select
        v-model="searchForm.code"
        placeholder="请选择国家"
        @change="onSearch"
      >
        <el-option
          v-for="item in regionsCountries"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-tree
        class="cus-tree"
        node-key="id"
        :data="regionTree"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :default-expanded-keys="defaultExpandedKeys"
      />
    </div>
    <!-- 行政区域列表 -->
    <div style="flex: 1; padding: 10px">
      <el-text class="cus-title">{{ selectedRegion ? selectedRegion.name : "" }}</el-text>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" @click="onAddRegion" icon="CirclePlus"
        >新增区域</el-button
      >
      <el-divider direction="horizontal"></el-divider>
      <el-table
        :data="selectedChildRegions"
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column prop="code" label="区域编码" />
        <el-table-column prop="name" label="区域名称" />
        <el-table-column prop="level" label="级别" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="onEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              @click="onDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 新增行政区域对话框 -->
  <el-dialog v-model="dialogVisible" title="新增区域" width="30%"       header-class="dialog-custom-header"
  >
  <el-divider direction="horizontal" style="width: 95%"></el-divider>

    <el-form :model="newRegionForm" label-width="70px">
      <el-form-item label="区域编码" v-if="!isEditRegion">
        <el-input v-model="newRegionForm.code" />
      </el-form-item>
      <el-form-item label="区域名称">
        <el-input v-model="newRegionForm.name" />
      </el-form-item>
      <el-form-item label="级别" v-if="!isEditRegion">
        <el-select v-model="newRegionForm.level" placeholder="级别">
          <el-option
            v-for="item in regionLevels"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="父区域编码" v-if="false">
        <el-input v-model="newRegionForm.parent" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmitRegion">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { get, post, put, del } from "@/utils/request";
import { ElMessage } from "element-plus";
const regionsCountries = ref([]);
const regionTree = ref([]);
const selectedRegion = ref(null);
const defaultProps = {
  children: "children",
  label: "name",
};
const isEditRegion = ref(false);
const searchForm = reactive({
  code: null,
});
const regionLevels = ref([
  {
    label: "国家",
    value: 1,
  },
  {
    label: "州/省",
    value: 2,
  },
  {
    label: "市",
    value: 3,
  },
  {
    label: "区/县",
    value: 4,
  },
]);

const selectedChildRegions = ref([]);

const handleNodeClick = (data) => {
  selectedRegion.value = data;
  selectedChildRegions.value = data.children || [];
};
const defaultExpandedKeys = ref([]);
const dialogVisible = ref(false);
const newRegionForm = reactive({
  id: null,
  code: null,
  name: null,
  level: null,
  parent: null,
  country: null,
});

const onSubmitRegion = async () => {
  let succ = false;
  if (isEditRegion.value) {
    let payload = {
      name: newRegionForm.name,
    };
    await put("/edm/regions/" + newRegionForm.id, payload)
      .then((res) => {
        if (res.data.code === 0) {
          onSearch(searchForm.code);
          succ = true;
          ElMessage.success("修改成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  } else {
    let payload = {
      code: newRegionForm.code,
      name: newRegionForm.name,
      level: newRegionForm.level,
      parent: newRegionForm.parent,
      country: newRegionForm.country,
    };
    await post("/edm/regions", payload)
      .then((res) => {
        if (res.data.code === 0) {
          onSearch(searchForm.code);
          succ = true;
          ElMessage.success("新增成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
  if (succ) {
    dialogVisible.value = false;
  }
};

const findParent = (tree, parent) => {
  for (const node of tree) {
    if (node.code === parent) {
      return node;
    }
    if (node.children) {
      const result = findParent(node.children, parent);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

const onAddRegion = () => {
  if (!selectedRegion.value) {
    ElMessage.error("请先选中父级区域");
    return;
  }
  Object.keys(newRegionForm).forEach((key) => {
    newRegionForm[key] = null;
  });
  newRegionForm.parent = selectedRegion.value.code;
  newRegionForm.country = searchForm.code;
  isEditRegion.value = false;
  dialogVisible.value = true;
};
const onEdit = (row) => {
  // 编辑逻辑
  console.log("编辑", row);
  isEditRegion.value = true;
  Object.assign(newRegionForm, row);
  dialogVisible.value = true;
};

const onDelete = (row) => {
  del("/edm/regions/" + row.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        onSearch(searchForm.code);
        ElMessage.success("删除成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onSearch = (val) => {
  // 根据搜索条件，更新菜单树
  let params = {
    code: val,
  };
  get("/edm/regions", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        regionTree.value = res.data.data.data;
        if (regionTree.value.length > 0) {
          let root = regionTree.value[0];
          defaultExpandedKeys.value = [];
          defaultExpandedKeys.value.push(root.id);
        }
        selectedChildRegions.value = [];
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

onMounted(async () => {
  // 获取顶级菜单列表
  await get("/edm/regions/countries")
    .then((res) => {
      if (res.data.code === 0) {
        regionsCountries.value = res.data.data.data;
        searchForm.code = regionsCountries.value[0].value;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        if (res.data.message) {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        } else {
          ElMessage.error(res.data.msg);
        }
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
  onSearch(searchForm.code);
});


</script>


